package test.niit.edu.cn.android1920;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;

/**
 * Created by CWork on 2019-9-9.
 */

public class StudentOP {
    DBHelper dbHelper;
    SQLiteDatabase db;
    public StudentOP(Context context){
        dbHelper = new DBHelper(context);
    }

    public void open()throws SQLException{
        db = dbHelper.getWritableDatabase();
    }
    public void close(){
        dbHelper.close();
    }
    //数据库的具体操作：增、删、改、查
    public ArrayList<Object> getStuInfo(   ){
        ArrayList<Object> students = new ArrayList<Object>();
        Cursor cursor = db.query(DBHelper.TABLE_NAME,null,null,null,null,null,null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()){
            StudentBean student = new StudentBean();
            student.setId(cursor.getInt(0));
            student.setName(cursor.getString(1));
            students.add(student);
            cursor.moveToNext();
        }
        cursor.close();
        return students;
    }
    public StudentBean addStudent(String name){
        ContentValues values = new ContentValues();
        values.put(DBHelper.STUDENT_NAME,name);
        long studID = db.insert(DBHelper.TABLE_NAME,null,values);
        Cursor cursor = db.query(DBHelper.TABLE_NAME,null,
                DBHelper.STUDENT_ID +"="+studID,null,null,null,null);
        cursor.moveToFirst();
        StudentBean newComment = new StudentBean();
        newComment.setId(cursor.getInt(0));
        newComment.setName(cursor.getString(1));
        cursor.close();
        return newComment;
    }

    public void deleteStudent(StudentBean comment){
        long id = comment.getId();
//        db.execSQL("delete from "+DBHelper.TABLE_NAME+" where "+
//                DBHelper.STUDENT_ID+" = "+id);
        db.delete(DBHelper.TABLE_NAME,DBHelper.STUDENT_ID+" = "+id,null);
    }


}
